package com.yunbao.live.views;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.live.R;
import com.yunbao.live.http.LiveHttpConsts;
import com.yunbao.live.http.LiveHttpUtil;
// +----------------------------------------------------------------------
// | Created by Yunbao
// +----------------------------------------------------------------------
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: https://gitee.com/yunbaokeji/
// +----------------------------------------------------------------------
// | Date: 2022-02-17
// +----------------------------------------------------------------------
/**
 * 直播间播放器  腾讯播放器
 */

public class LivePlayTxViewHolder extends LiveRoomPlayViewHolder implements ITXLivePlayListener {

    private static final String TAG = "LiveTxPlayViewHolder";
    private ViewGroup mRoot;
    private TXCloudVideoView mVideoView;
    private View mLoading;
    private ImageView mCover;
    private TXLivePlayer mPlayer;
    private boolean mPaused;//是否切后台了
    private boolean mStarted;//是否开始了播放
    private boolean mEnd;//是否结束了播放
    private boolean mPausedPlay;//是否被动暂停了播放
    private Handler mHandler;
    private int mVideoLastProgress;
    private float mVideoWidth;
    private float mVideoHeight;


    public LivePlayTxViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_live_play_tx;
    }

    @Override
    public void init() {
        mRoot = (ViewGroup) findViewById(R.id.root);
        mLoading = findViewById(R.id.loading);
        mCover = (ImageView) findViewById(R.id.cover);
        mVideoView = (TXCloudVideoView) findViewById(R.id.video_view);

        mPlayer = new TXLivePlayer(mContext);
        mPlayer.setPlayListener(this);
        mPlayer.setPlayerView(mVideoView);
        mPlayer.enableHardwareDecode(false);
        mPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
        mPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
        TXLivePlayConfig playConfig = new TXLivePlayConfig();
        playConfig.setAutoAdjustCacheTime(true);
        playConfig.setMaxAutoAdjustCacheTime(5.0f);
        playConfig.setMinAutoAdjustCacheTime(1.0f);
        playConfig.setHeaders(CommonAppConfig.HEADER);
        mPlayer.setConfig(playConfig);

    }


    @Override
    public void onPlayEvent(int e, Bundle bundle) {
        if (mEnd) {
            return;
        }
        switch (e) {
            case TXLiveConstants.PLAY_EVT_PLAY_BEGIN://播放开始
                if (mLoading != null && mLoading.getVisibility() == View.VISIBLE) {
                    mLoading.setVisibility(View.INVISIBLE);
                }
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_LOADING:
                if (mLoading != null && mLoading.getVisibility() != View.VISIBLE) {
                    mLoading.setVisibility(View.VISIBLE);
                }
                break;
            case TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME://第一帧
                hideCover();
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_END://播放结束
                replay();
                break;
            case TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION://获取视频宽高
                mVideoWidth = bundle.getInt("EVT_PARAM1", 0);
                mVideoHeight = bundle.getInt("EVT_PARAM2", 0);
                changeVideoSize(false);
                break;
            case TXLiveConstants.PLAY_ERR_NET_DISCONNECT://播放失败
            case TXLiveConstants.PLAY_ERR_FILE_NOT_FOUND:
                ToastUtil.show(WordUtil.getString(R.string.live_play_error));
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                int progress = bundle.getInt("EVT_PLAY_PROGRESS_MS");
                if (mVideoLastProgress == progress) {
                    replay();
                } else {
                    mVideoLastProgress = progress;
                }
                break;
        }
    }


    public void changeVideoSize(boolean landscape) {
        if (mVideoWidth > 0 && mVideoHeight > 0) {
            float videoRatio = mVideoWidth / mVideoHeight;
            float p1 = mParentView.getWidth();
            float p2 = mParentView.getHeight();
            float parentWidth = p1;
            float parentHeight = p2;
            if (landscape) {
                parentWidth = Math.max(p1, p2);
                parentHeight = Math.min(p1, p2);
            } else {
                parentWidth = Math.min(p1, p2);
                parentHeight = Math.max(p1, p2);
            }
            float parentRatio = parentWidth / parentHeight;
            if (videoRatio != parentRatio) {
                FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) mVideoView.getLayoutParams();
                if (videoRatio > 10f / 16f && videoRatio > parentRatio) {
                    p.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    p.height = (int) (parentWidth / videoRatio);
                    p.gravity = Gravity.CENTER;
                } else {
                    p.width = (int) (parentHeight * videoRatio);
                    p.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    p.gravity = Gravity.CENTER;
                }
                mVideoView.requestLayout();
            }
        }
    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }


    @Override
    public void hideCover() {
        if (mCover != null) {
            mCover.animate().alpha(0).setDuration(500).start();
        }
    }

    @Override
    public void setCover(String coverUrl) {
        if (mCover != null) {
            ImgLoader.displayBlur(mContext, coverUrl, mCover);
        }
    }

    /**
     * 循环播放
     */
    private void replay() {
        if (mStarted && mPlayer != null) {
            mPlayer.seek(0);
            mPlayer.resume();
        }
    }


    /**
     * 暂停播放
     */
    @Override
    public void pausePlay() {
        if (!mPausedPlay) {
            mPausedPlay = true;
            if (!mPaused) {
                if (mPlayer != null) {
                    mPlayer.setMute(true);
                }
            }
            if (mCover != null) {
                mCover.setAlpha(1f);
                if (mCover.getVisibility() != View.VISIBLE) {
                    mCover.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 暂停播放后恢复
     */
    @Override
    public void resumePlay() {
        if (mPausedPlay) {
            mPausedPlay = false;
            if (!mPaused) {
                if (mPlayer != null) {
                    mPlayer.setMute(false);
                }
            }
            hideCover();
        }
    }

    /**
     * 开始播放
     *
     * @param url 流地址
     */
    @Override
    public void play(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        try {
            int playType = -1;
            if (url.startsWith("rtmp://")) {
                playType = TXLivePlayer.PLAY_TYPE_LIVE_RTMP;
            } else if (url.contains(".flv")) {
                playType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
            } else if (url.contains(".m3u8")) {
                playType = TXLivePlayer.PLAY_TYPE_VOD_HLS;
            } else if (url.contains(".mp4")) {
                playType = TXLivePlayer.PLAY_TYPE_VOD_MP4;
            }
            if (playType == -1) {
                ToastUtil.show(R.string.live_play_error_2);
                return;
            }
            if (mPlayer != null) {
                int result = mPlayer.startPlay(url, playType);
                if (result == 0) {
                    mStarted = true;
                }
            }
            L.e(TAG, "play----url--->" + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stopPlay() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mCover != null) {
            mCover.setAlpha(1f);
            if (mCover.getVisibility() != View.VISIBLE) {
                mCover.setVisibility(View.VISIBLE);
            }
        }
        stopPlay2();
    }

    @Override
    public void stopPlay2() {
        if (mPlayer != null) {
            mPlayer.stopPlay(false);
        }
    }

    @Override
    public void release() {
        mEnd = true;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mHandler = null;
        if (mPlayer != null) {
            mPlayer.stopPlay(false);
            mPlayer.setPlayListener(null);
        }
        mPlayer = null;
        L.e(TAG, "release------->");
    }




    @Override
    public void onResume() {
        if (!mPausedPlay && mPaused && mPlayer != null) {
            mPlayer.setMute(false);
        }
        mPaused = false;
    }

    @Override
    public void onPause() {
        if (!mPausedPlay && mPlayer != null) {
            mPlayer.setMute(true);
        }
        mPaused = true;
    }

    @Override
    public void onDestroy() {
        release();
    }


}
